package com.scs.application.modules.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.entity.Matr;
import com.scs.application.modules.base.entity.MatrUnit;
import com.scs.application.modules.base.mapper.MatrMapper;
import com.scs.application.modules.base.mapper.MatrUnitMapper;
import com.scs.application.modules.base.service.MatrUnitService;
import com.scs.application.modules.wm.entity.Stock;
import com.scs.application.modules.wm.entity.WorkOrderItem;
import com.scs.application.modules.wm.mapper.StockMapper;
import com.scs.application.modules.wm.mapper.WorkOrderItemMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 耗材单位 服务实现类
 * </p>
 */
@Service
public class MatrUnitServiceImpl extends BaseServiceImpl<MatrUnitMapper, MatrUnit> implements MatrUnitService {

    @Autowired
    private MatrMapper matrMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private WorkOrderItemMapper workOrderItemMapper;

    @Override
    public boolean saveOrUpdate(MatrUnit entity) {
        MatrUnit matrunit = new MatrUnit();
        if(entity.id != null){
            matrunit = this.getOne(Wrappers.<MatrUnit>query().eq("id",entity.id));
        }
        List<WorkOrderItem> workOrderItems = workOrderItemMapper.selectList(Wrappers.<WorkOrderItem>query().eq("matr_id", entity.getMatrId()).eq("package_unit", matrunit.getUnit()));
        //若只修改采购属性，禁用属性，请领属性则不提示
        if (!entity.isNewRecord() && workOrderItems.size() > 0) {
            throw new BusinessException("该耗材的包装单位已有出入库记录，不允许修改单位");
        }
        entity.setUnit(StringUtils.trim(entity.getUnit()));
        //该耗材是否已有该单位
        int hitCount = super.count(Wrappers.<MatrUnit>query()
                .eq("matr_id", entity.getMatrId())
                .eq("unit", StringUtils.trim(entity.getUnit()))
                .ne(!entity.isNewRecord(), "id", entity.getId()));
        if (hitCount > 0) throw new BusinessException("该耗材已有同名的包装单位，请换用其他名称");
        if (!entity.getFlagBase()) {
            return super.saveOrUpdate(entity);
        }
        // 不允许单品单位存在多个
        if (entity.getFlagBase() != null && entity.getFlagBase() ) {
            int count = this.count(Wrappers.<MatrUnit>query().eq("matr_id", entity.getMatrId()).eq("flag_base", true).ne(StringUtils.isNotBlank(entity.getId()), "id",entity.getId()));
            if (count >= 1) {
                // todo 已存在单品单位，抛出异常 OR 直接修改？
                throw new BusinessException("只允许同时存在一个单品单位");
            }

        }

        if (entity.getRate() != 1) throw new BusinessException("单品单位，比率必须为1");

        //修改基础单位后同步其他单位价格
        MatrUnit matrUnit = super.getById(entity.getId());
        if (matrUnit != null && !matrUnit.getPrice().equals(entity.getPrice())) {
            List<MatrUnit> matrUnitList = super.list(new QueryWrapper<MatrUnit>().eq("matr_id", entity.getMatrId())
                    .eq("flag_base", false));
            if (matrUnitList.size() > 0) {
                List<MatrUnit> matrUnitList1 = matrUnitList.stream().map(unit -> {
                    MatrUnit matrUnit1 = new MatrUnit();
                    matrUnit1.setPrice(unit.getRate() * entity.getPrice())
                            .setId(unit.getId());
                    return matrUnit1;
                }).collect(Collectors.toList());
                super.saveOrUpdateBatch(matrUnitList1);
            }
        }

        //修改关联耗材
        Matr matr = new Matr();
        matr.setSkuUnit(entity.getUnit()).setSkuPrice(entity.getPrice())
                .setId(entity.getMatrId());
        matrMapper.updateById(matr);
        return super.saveOrUpdate(entity);
    }

    @Override
    public boolean removeCascadeByIds(Collection<? extends Serializable> idList) {
        List<String> matrIds = super.list(Wrappers.<MatrUnit>query().in("id", idList)).stream().map(MatrUnit::getMatrId).collect(Collectors.toList());
        List<String> matrUnits = super.list(Wrappers.<MatrUnit>query().in("id", idList)).stream().map(MatrUnit::getUnit).collect(Collectors.toList());
        if (matrIds != null && matrIds.size() > 0 && stockMapper.list(Wrappers.<Stock>query().in("matr_id", matrIds).in("package_unit", matrUnits).gt("sku_qty",0)).size() > 0) {
            throw new BusinessException("该耗材的包装单位已有库存记录，不允许删除单位");
        }
        return super.removeCascadeByIds(idList);
    }

    @Override
    public Page<Map> pageForSelect(QueryContext context, Map<String, Object> userParam) {
        return this.baseMapper.pageForSelect(context.getPage(), context.getWrapper(), context.getParams(), userParam);
    }

    @Override
    public boolean updateItem(MatrUnit entity) {

        return   this.update(Wrappers.<MatrUnit>update()
                .set("flag_purchase", entity.getFlagPurchase())
                .set("flag_apply", entity.getFlagApply()).eq("id",entity.getId()));
    }

    @Override
    public Double getPackageRateByMatrIdAndUnitName(String matrId, String packageUnit) {
        MatrUnit matrUnit = this.getOne(Wrappers.<MatrUnit>query().eq("matr_id",matrId).eq("unit",packageUnit),false);
        BusinessException.throwValidFailIf(matrUnit==null, "该商品未找到单位，商品id:%s，单位名称:%s",matrId,packageUnit);
        return matrUnit.getRate();
    }
}
